import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { Menu } from "../../../../entity/menu.model";
import { Observable } from "rxjs/Observable";
import { Command } from "../../../../shared/toolbar.service";
import { Blade } from "../../../../shared/blade/blade.model";
import { BladeData } from "../../../../shared/blade/blade-data";
import { MenuEditComponent } from "../menu-edit/menu-edit.component";
import { MenuService } from "../../../../service/menu.service";
import { TreeNode } from "primeng/primeng";
import { List } from "linqts";
import { DialogResult } from "../../../../shared/dialog.service";
import { MenuParamListComponent } from "../menu-param-list/menu-param-list.component";

@Component({
  selector: 'app-menu-list',
  templateUrl: './menu-list.component.html',
  styleUrls: ['./menu-list.component.css']
})
export class MenuListComponent extends BladeContainerBase<Menu> {
  /**
   * 根节点
   * 
   * @private
   * @type {Menu}
   * @memberof MenuListComponent
   */
  private rootMenu: Menu = new Menu(0, "Root", "", "", "", 1, null, 0, []);
  /**
   * 所有节点
   * 
   * @type {TreeNode[]}
   * @memberof MenuListComponent
   */
  public files: TreeNode[] = [];
  public selectedFile: TreeNode[] = [];


  /**
   * 所有菜单
   * 
   * @private
   * @type {Menu[]}
   * @memberof MenuListComponent
   */
  private menus: Menu[] = [this.rootMenu];



  constructor(private menuService: MenuService) {
    super();
    this.commands = [
      new Command("add", "添加", "fa fa-plus", "menu:insert", blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command("delete", "删除", "fa fa-trash-o", "menu:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade)),
      new Command("edit", "编辑参数", "fa fa-edit", "menu:update", blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
    ];
  }
  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = "menuEdit";
    data.title = "菜单创建";
    data.subtitle = "创建一个菜单";
    data.isClosingDisabled = false;
    let createMenuBlade = this.bladeService.createBlade(MenuEditComponent, data, true, null, {
      menus: this.menus,
      parent: this.currentEntity
    });
    this.bladeService.showBlade(createMenuBlade, this.currentBlade);
  }
  canExeAdd(blend: Blade): boolean {
    return true;
  }
  exeEdit(blend: Blade): void {
    if (this.currentEntity != undefined) {
      this.showMenuParamListBlade(this.currentEntity)
    }
  }
  canExeEdit(blend?: Blade): boolean {
    return this.currentEntity != null;
  }
  exeDelete(blend: Blade): void {

    let selectedMenus = this.getSelected();
    if (selectedMenus.length > 0) {
      this.dialogService
        .showConfirmationDialog("确认删除", "是否要删除选中项？")
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;

            this.menuService.batchDelete(selectedMenus.map(o => o.menuId))
              .then(res => {
                if (res.code == '200') {
                  this.bladeService.closeBlade(this.currentBlade.childrenBlades[0]);
                  super.refresh(undefined);

                }
                if (res.code == '8001') {
                  this.dialogService
                    .showConfirmationDialog("删除失败", res.message);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }
  }

  canDelete(blend: Blade): boolean {
    return this.getSelected().length > 0;
  }

  /**
   * 初始化数据
   * 
   * 
   * @memberof BladeContainerBase
   */
  initData(): any | Observable<any> | Promise<any> {

    this.menuService.getMenus()
      .then(res => {
        if (!res) { return false; };
        this.bladeData.isLoading = false;
        this.rootMenu.isChecked = false
        this.menus = [this.rootMenu];
        this.menus.push(...res);
        this.files = [];
        let firstMenus = this.menus.filter(o => o.parentId == 0);
        let level: number = 2;
        this.rootMenu.menuLevel = 1;
        let treeNode: TreeNode = {};
        treeNode.data = this.rootMenu;

        this.files.push(treeNode);

        if (firstMenus != null) {

          firstMenus = new List(firstMenus).OrderBy(o => o.menuSeq).ToArray();
          this.rootMenu.children = firstMenus;
          firstMenus.forEach(menu => {
            /* menu.menuLevel = level;
            let treeNode: TreeNode = {};
            treeNode.data = menu;
            this.files.push(treeNode); */
            menu.menuLevel = level;
            let childernTreeNode: TreeNode = {};
            childernTreeNode.data = menu;
            if (!treeNode.children) {
              treeNode.children = [];
            }
            treeNode.children.push(childernTreeNode);
            this.initChildMenu(menu, childernTreeNode);
          });
        }
      })
      .catch(err => {
        this.bladeData.error = err;
      });
  }
  /**
   * 递归初始化子菜单
   * 
   * @param {Menu} menu 
   * @param {TreeNode} treeNode 
   * @memberof MenuListComponent
   */
  initChildMenu(menu: Menu, treeNode: TreeNode) {
    let childrenMenus = this.menus.filter(o => o.parentId == menu.menuId);
    if (childrenMenus != null && childrenMenus.length > 0) {
      let level: number = menu.menuLevel + 1;
      let list = new List(childrenMenus);
      let childrenTemp = list.OrderBy(o => o.menuSeq).ToArray();
      menu.children = childrenTemp;
      menu.children.forEach(childrenMenu => {
        childrenMenu.menuLevel = level;
        let childernTreeNode: TreeNode = {};
        childernTreeNode.data = childrenMenu;
        if (!treeNode.children) {
          treeNode.children = [];
        }
        treeNode.children.push(childernTreeNode);
        //递归
        this.initChildMenu(childrenMenu, childernTreeNode);
      });
    }
  }

  getSelected(): Menu[] {
    if (this.menus.length > 0) {
      let filter = this.menus.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }

  public onNodeSelect(event: any) {
    let node: TreeNode = event.node;
    node.expanded = !node.expanded;
    let menu = event.node.data;
    this.currentEntity = menu;
    if (menu.menuId) {
      this.showCompanyEditBlade(menu);
    } 


  }


  /**
    * 单选
    * 
    * @param {any} event 
    * @param {any} key 
    * 
    * @memberof 
    */
  onItemCheack(event: HTMLInputElement, menu: Menu) {
    this.setChildrenChecked(menu, event.checked);
    // this.setParenChecked(menu);   
  }

  /**
   * 设置子菜单是否选中
   * 
   * @param {Menu} menu 
   * @param {boolean} isChecked 
   * @memberof MenuListComponent
   */
  setChildrenChecked(menu: Menu, isChecked: boolean) {
    menu.isChecked = isChecked;
    if (menu.children && menu.children.length) {
      menu.children.forEach(childMenu => {
        this.setChildrenChecked(childMenu, isChecked);
      });
    }
  }

  /**
   * 设置父菜单是否选中
   * 
   * @param {Menu} menu 
   * @memberof MenuListComponent
   */
  setParenChecked(menu: Menu) {
    let parenMenu = this.menus.find(o => o.menuId == menu.parentId);
    if (parenMenu != null) {
      let isCheckedCount = parenMenu.children.filter(o => o.isChecked).length;
      if (isCheckedCount == parenMenu.children.length) {
        parenMenu.isChecked = true;
      }
      else {
        parenMenu.isChecked = false;
      }
      this.setParenChecked(parenMenu);
    }
  }

  /**
   * 展开菜单编辑弹出层
   * 
   * @param {Setofkey} selectedKey 
   * 
   * @memberof DicKeyListComponent
   */
  showCompanyEditBlade(menu: Menu) {

    if (this.currentEntity != menu
      || this.bladeService.findBlade("menuEditBlade") == undefined) {
      let data: BladeData = new BladeData();
      data.id = "menuEditBlade";
      data.title = menu.menuName + "编辑";
      data.subtitle = menu.menuSubName;
      data.isClosingDisabled = false;

      let dicValueListBlade = this.bladeService.createBlade(MenuEditComponent, data, false, menu, { menus: this.menus });

      this.bladeService.showBlade(dicValueListBlade, this.currentBlade).then(res => {
        if (res) {
          this.currentEntity = menu;
        }
      });
    }
  }


  /**
   * 展开菜单参数列表弹出层
   * 
   * @param {Setofkey} selectedKey 
   * 
   * @memberof DicKeyListComponent
   */
  showMenuParamListBlade(menu: Menu) {
    let data: BladeData = new BladeData();
    data.id = "menuParamList";
    data.title = menu.menuName + "参数列表";
    data.isClosingDisabled = false;
    let dicValueListBlade = this.bladeService.createBlade(MenuParamListComponent, data, false, null, menu);
    this.bladeService.showBlade(dicValueListBlade, this.currentBlade)
  }

}



// WEBPACK FOOTER //
// ./src/app/module/admin/menu/menu-list/menu-list.component.ts